<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="shake.js"></script>
<body>
<div style="width:100px;height:100px;margin:100px auto;background-color:#333;" id="but"></div>
<span id="num"></span>
<script>
var socket = new WebSocket('ws://192.168.2.110:8282');
socket.onopen = function(event){
	var count=1;
	//alert('连接成功！');
	message='{"type":"login","count":'+count+'}';
	socket.send(message);
	//摇一摇
	init();
	var SHAKE_THRESHOLD = 2000;
	        var last_update = 0;
	        var x = y = z = last_x = last_y = last_z = 0;
	        function init() {
	            if (window.DeviceMotionEvent) {
	                window.addEventListener('devicemotion', deviceMotionHandler, false);
	            } else {
	                alert('not support mobile event');
	            }
	        }
	        function deviceMotionHandler(eventData) {
	            var acceleration = eventData.accelerationIncludingGravity;
	            var curTime = new Date().getTime();
	            if ((curTime - last_update) > 100) {
	                var diffTime = curTime - last_update;
	                last_update = curTime;
	                x = acceleration.x;
	                y = acceleration.y;
	                z = acceleration.z;
	                var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

	                if (speed > SHAKE_THRESHOLD) {
	                	count+=5;
	                    message='{"type":"update","count":'+count+'}'
	                    socket.send(message);
	                }
	                last_x = x;
	                last_y = y;
	                last_z = z;
	            }
	        }
	//
	socket.onmessage = function(event){
		str=event.data;
		var obj = eval('(' + str + ')');
		$("#num").html(count);
		};
	}
</script>
</body>
</html>